package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

type xkcd struct {
	SafeTitle string `json:"safe_title"`
	Img       string
}

func Getxkcd() ([]*xkcd, error) {
	var xkcds []*xkcd
	for i := 1; i < 5; i++ {
		url := fmt.Sprintf("https://xkcd.com/%d/info.0.json", i)
		resp, err := http.Get(url)
		if err != nil {
			fmt.Println(err)
			continue
		}
		if resp.StatusCode != http.StatusOK {
			resp.Body.Close()
			fmt.Printf("get %s failed: %s\n", url, resp.Status)
			continue
		}
		var xkcd xkcd
		if err := json.NewDecoder(resp.Body).Decode(&xkcd); err != nil {
			resp.Body.Close()
			fmt.Printf("decode %s failed: %s\n", url, err)
			continue
		}
		resp.Body.Close()
		xkcds = append(xkcds, &xkcd)
	}
	return xkcds, nil

}
func main() {
	key := os.Args[1]
	xkcds, err := Getxkcd()
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, xkcd := range xkcds {
		if xkcd.SafeTitle == key {
			fmt.Println(xkcd.Img)
			return
		}
		fmt.Println(xkcd.SafeTitle, xkcd.Img)
		fmt.Println("not found")
	}
}
